<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" style="margin-top: 20px">
      <template #expr="{ model, field }">
        <InputTextArea
          :row="5"
          v-model:value="model[field]"
          ref="InputTextAreaRef"
          @focus="handleFocusInputTextArea(model[field])"
          style="height: 100px"
        />
      </template>
    </BasicForm>
    <template v-if="dataRef.ruleType == 'connector'">
      <div>
        <BodyHeaderList
          title="Headers"
          :formCode="formCode"
          v-model:modelValue="dataRef.headers"
          v-model:nameList="headersList"
        />
      </div>
      <div>
        <BodyHeaderList
          title="参数"
          :formCode="formCode"
          v-model:modelValue="dataRef.body"
          :nameList="bodyList"
        />
      </div>
      <div>
        <ResultList
          title="结果"
          :formCode="formCode"
          v-model:modelValue="dataRef.result"
          :nameList="resultList"
        />
      </div>
    </template>
    <ExprModal @register="registerExprModal" @success="handleExprModalSuccess" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Input } from 'ant-design-vue';
  import {
    getAdminFlowActions,
    getConnectorList,
    getConnectorListAction,
  } from '/@/api/flowManage/flowManage';
  import { ExprModal } from '/@/components/CustomComp';
  import BodyHeaderList from './BodyHeaderList.vue';
  import ResultList from './ResultList.vue';
  import { isArray } from '/@/utils/is';
  import { buildUUID } from '/@/utils/uuid';
  import { deepClone } from '/@/views/formDesigner/utils';

  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      InputTextArea: Input.TextArea,
      ExprModal,
      BodyHeaderList,
      ResultList,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      let isUpdate = ref(true);
      let dataRef = ref<Recordable>({});
      const typeCode = ref('');
      const formCode = ref('');

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false, width: '50%' });
        isUpdate.value = !!data?.isUpdate;
        typeCode.value = data.typeCode;
        formCode.value = data.formCode;
        getActionList();
        getConnectorListData();
        if (unref(isUpdate)) {
          dataRef.value = deepClone(data.record);
          console.log('dataRef', dataRef.value);
          setFieldsValue({
            ...dataRef.value,
          });

          if (dataRef.value.connector) {
            getConnectorListActionData(dataRef.value.connector).then(() => {
              if (dataRef.value.action) {
                const record: any = connectorListAction.value.find(
                  (item) => item.id == dataRef.value.action,
                );
                console.log('useModalInner record', record);
                if (record) {
                  if (isArray(record.body)) {
                    bodyList.value = record.body.map((item) => {
                      item.label = item.name;
                      return { ...item };
                    });
                    if (isArray(dataRef.value.body)) {
                      dataRef.value.body.forEach((item) => {
                        item.nameList = [];
                        if (item.name) {
                          item.nameList = bodyList.value.filter((el) => el.name == item.name);
                        }
                      });
                    } else {
                      dataRef.value.body = [];
                    }
                  }
                  if (isArray(record.headers)) {
                    headersList.value = record.headers.map((item) => {
                      item.label = item.name;
                      return { ...item };
                    });
                    if (isArray(dataRef.value.headers)) {
                      dataRef.value.headers.forEach((item) => {
                        item.nameList = [];
                        if (item.name) {
                          item.nameList = headersList.value.filter((el) => el.name == item.name);
                        }
                      });
                    } else {
                      dataRef.value.headers = [];
                    }
                  }

                  if (isArray(record.result)) {
                    resultList.value = record.result.map((item) => {
                      item.label = item.name;
                      return { ...item };
                    });

                    if (isArray(dataRef.value.result)) {
                      dataRef.value.result.forEach((item) => {
                        item.nameList = [];
                        if (item.name) {
                          item.nameList = resultList.value.filter((el) => el.name == item.name);
                        }
                      });
                    } else {
                      dataRef.value.result = [];
                    }
                    console.log('useModalInner dataRef.value.result', dataRef.value.result);
                  }
                }
              }
            });
          }
        } else {
          dataRef.value = {
            ruleType: 'op',
            nodeOperate: 'agree',
            id: buildUUID(),
          };
          setFieldsValue({
            ...dataRef.value,
          });
        }
        if (dataRef.value.ruleType == 'op') {
          updateSchema({
            field: 'expr',
            label: '关联操作',
          });
        } else {
          updateSchema({
            field: 'expr',
            label: '校验规则',
          });
        }
      });

      const connectorList = ref([]);
      //获取连接器
      const getConnectorListData = () => {
        getConnectorList().then((res) => {
          connectorList.value = res || [];
          updateSchema({
            field: 'connector',
            componentProps: {
              treeData: connectorList.value,
            },
          });
        });
      };
      const connectorListAction = ref<any[]>([]);
      //获取连接器动作
      const getConnectorListActionData = async (id) => {
        connectorListAction.value = [];
        if (!id) return;
        await getConnectorListAction({ id }).then((res) => {
          connectorListAction.value = res || [];
          updateSchema({
            field: 'action',
            componentProps: {
              treeData: connectorListAction.value,
            },
          });
        });
      };
      const bodyList = ref<any[]>([]);
      const headersList = ref<any[]>([]);
      const resultList = ref<any[]>([]);
      const handleChangeAction = (value) => {
        bodyList.value = [];
        headersList.value = [];
        resultList.value = [];
        dataRef.value.body = [];
        dataRef.value.headers = [];
        dataRef.value.result = [];
        if (value) {
          const record: any = connectorListAction.value.find((item) => item.id == value);
          console.log('handleChangeAction record', record);
          if (record) {
            if (isArray(record.body)) {
              bodyList.value = record.body.map((item) => {
                item.label = item.name;
                return { ...item };
              });
              console.log('handleChangeAction bodyList', bodyList.value);
            }
            if (isArray(record.headers)) {
              headersList.value = record.headers.map((item) => {
                item.label = item.name;
                return { ...item };
              });
            }
            if (isArray(record.result)) {
              resultList.value = record.result.map((item) => {
                item.label = item.name;
                return { ...item };
              });
            }
            console.log('handleChangeAction resultList', resultList.value);
          }
        }
      };
      //获取节点
      const actionList = ref([]);
      async function getActionList() {
        if (!typeCode.value) return;
        await getAdminFlowActions({ typeCode: typeCode.value }).then((res) => {
          let data = res || [];
          data.forEach((item) => {
            item.value = item.internalName;
            item.label = item.jobName + ' : ' + item.title;
          });
          actionList.value = data;
          updateSchema({
            field: 'node',
            componentProps: {
              treeData: actionList.value,
            },
          });
        });
      }
      const FormSchema: FormSchema[] = [
        {
          field: 'title',
          label: '规则名称',
          component: 'Input',
          required: true,
          colProps: {
            span: 23,
          },
        },
        {
          field: 'selectNode',
          label: '选择节点',
          component: 'Divider',
          required: true,
          colProps: {
            span: 23,
          },
        },
        {
          field: 'nodeType',
          label: '类别',
          component: 'RadioGroup',
          colProps: { span: 23 },
          defaultValue: 'finished',
          required: true,
          componentProps: {
            options: [
              { label: '结束事件', value: 'finished' },
              { label: '审批节点', value: 'node' },
              { label: '前台请求', value: 'request' },
            ],
            onChange: (e) => {
              dataRef.value.nodeType = e.target.value;
              if (e.target.value == 'finished') {
                updateSchema({
                  field: 'ruleType',
                  componentProps: {
                    options: [
                      { label: '关联操作', value: 'op' },
                      { label: '连接器', value: 'connector' },
                    ],
                  },
                });
              } else if (e.target.value == 'request') {
                updateSchema({
                  field: 'ruleType',
                  componentProps: {
                    options: [{ label: '连接器', value: 'connector' }],
                  },
                });
                setFieldsValue({ ruleType: 'connector' });
                dataRef.value.ruleType = 'connector';
              } else {
                updateSchema({
                  field: 'ruleType',
                  componentProps: {
                    options: [
                      { label: '关联操作', value: 'op' },
                      { label: '校验规则', value: 'check' },
                      { label: '连接器', value: 'connector' },
                    ],
                  },
                });
              }
            },
          },
        },
        {
          field: 'node',
          label: '节点',
          component: 'TreeSelect',
          defaultValue: '',
          required: true,
          colProps: {
            span: 23,
          },
          componentProps: {
            treeData: actionList.value,
            fieldNames: { label: 'label', value: 'value' },
            showSearch: true,
            treeNodeFilterProp: 'label',
            getPopupContainer: () => document.body,
            onChange: (value, names) => {
              if (value) {
                dataRef.value.nodeName = names[0];
              }
            },
          },
          ifShow: ({ values }) => values.nodeType == 'node',
        },
        {
          field: 'rulesSet',
          label: '规则设置',
          component: 'Divider',
          required: true,
          colProps: {
            span: 23,
          },
        },
        {
          field: 'nodeOperate',
          label: '节点动作',
          component: 'RadioGroup',
          required: true,
          colProps: {
            span: 23,
          },
          defaultValue: 'agree',
          componentProps: {
            options: [
              { label: '同意', value: 'agree' },
              { label: '拒绝', value: 'disagree' },
              // { label: '保存', value: 'save' },
              { label: '退回', value: 'return' },
            ],
            onChange: (e) => {
              dataRef.value.nodeOperate = e.target.value;
              if (e.target.value == 'disagree' || e.target.value == 'return') {
                updateSchema({
                  field: 'ruleType',
                  componentProps: {
                    options: [
                      { label: '关联操作', value: 'op' },
                      { label: '连接器', value: 'connector' },
                    ],
                  },
                });
              } else {
                updateSchema({
                  field: 'ruleType',
                  componentProps: {
                    options: [
                      { label: '关联操作', value: 'op' },
                      { label: '校验规则', value: 'check' },
                      { label: '连接器', value: 'connector' },
                    ],
                  },
                });
              }
            },
          },
          show: ({ values }) => values.nodeType == 'node',
        },
        {
          field: 'ruleType',
          label: '规则类型',
          component: 'RadioGroup',
          colProps: { span: 23 },
          defaultValue: 'op',
          required: true,
          componentProps: {
            options: [
              { label: '关联操作', value: 'op' },
              { label: '校验规则', value: 'check' },
              { label: '连接器', value: 'connector' },
            ],
            onChange: (e) => {
              dataRef.value.ruleType = e.target.value;
              if (e.target.value == 'op') {
                updateSchema({
                  field: 'expr',
                  label: '关联操作',
                });
              } else {
                updateSchema({
                  field: 'expr',
                  label: '校验规则',
                });
              }
            },
          },
          // ifShow: ({ values }) => values.nodeType == 'node',
        },
        {
          field: 'expr',
          label: '关联操作',
          component: 'Input',
          required: true,
          colProps: {
            span: 23,
          },
          slot: 'expr',
          ifShow: ({ values }) => values.ruleType == 'op' || values.ruleType == 'check',
        },
        {
          field: 'connector',
          label: '连接器',
          component: 'TreeSelect',
          defaultValue: '',
          required: true,
          colProps: {
            span: 23,
          },
          componentProps: {
            treeData: connectorList.value,
            fieldNames: { label: 'name', value: 'id' },
            showSearch: true,
            treeNodeFilterProp: 'name',
            getPopupContainer: () => document.body,
            onChange: (value) => {
              setFieldsValue({ action: '' });
              getConnectorListActionData(value);
            },
          },
          ifShow: ({ values }) => values.ruleType == 'connector',
        },
        {
          field: 'action',
          label: '动作',
          component: 'TreeSelect',
          defaultValue: '',
          required: true,
          colProps: {
            span: 23,
          },
          componentProps: {
            treeData: connectorListAction.value,
            fieldNames: { label: 'name', value: 'id' },
            showSearch: true,
            treeNodeFilterProp: 'name',
            getPopupContainer: () => document.body,
            onChange: handleChangeAction,
          },
          ifShow: ({ values }) => values.ruleType == 'connector',
        },
      ];
      const [
        registerForm,
        { setFieldsValue, resetFields, validate, updateSchema, getFieldsValue },
      ] = useForm({
        labelWidth: 100,
        schemas: FormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const InputTextAreaRef = ref<HTMLElement | null>(null);
      const [registerExprModal, { openModal }] = useModal();

      const handleFocusInputTextArea = (expr) => {
        if (InputTextAreaRef.value) {
          InputTextAreaRef.value!.blur();
        }
        const form = getFieldsValue();
        openModal(true, {
          expr,
          isUpdate: true,
          fieldType: form.ruleType == 'op' ? 2 : 1, //2全部表单字段
        });
      };
      const handleExprModalSuccess = (val) => {
        setFieldsValue({
          expr: val,
        });
      };
      const getTitle = computed(() => (!unref(isUpdate) ? '增加' : '编辑'));
      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          const formData = Object.assign({}, dataRef.value, values);
          if (isArray(formData.body)) {
            formData.body.forEach((item) => {
              delete item.nameList;
            });
          }
          if (isArray(formData.headers)) {
            formData.headers.forEach((item) => {
              delete item.nameList;
            });
          }
          if (isArray(formData.result)) {
            formData.result.forEach((item) => {
              delete item.nameList;
            });
          }

          // code为连接器动作的编码
          if (connectorListAction.value && connectorListAction.value.length > 0) {
            formData.code = connectorListAction.value[0]['code'];
          }
          closeModal();
          console.log(
            'formData',
            formData,
            'dataRef',
            dataRef.value,
            'connectorListAction',
            connectorListAction.value,
          );
          emit('success', formData);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        handleFocusInputTextArea,
        registerExprModal,
        handleExprModalSuccess,
        InputTextAreaRef,
        formCode,
        bodyList,
        headersList,
        resultList,
        dataRef,
      };
    },
  });
</script>
